package com.ltx.blog_ltx.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ltx.blog_ltx.entity.pojo.Record;
import com.ltx.blog_ltx.mapper.ChatMapper;
import com.ltx.blog_ltx.mapper.UnreadNumMapper;
import com.ltx.blog_ltx.until.EmojiUntil;
import com.ltx.blog_ltx.until.SensitiveFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/socket/{userName}")
@Component
@Slf4j
public class WebSocketServer {

    private static ChatMapper chatMapper;

    private static UnreadNumMapper unreadNumMapper;

    @Autowired
    public void setChatService(ChatMapper chatMapper) {
        WebSocketServer.chatMapper=chatMapper;
    }
    @Autowired
    public void setUnreadNumMapperService(UnreadNumMapper unreadNumMapper) {
        WebSocketServer.unreadNumMapper=unreadNumMapper;
    }

    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName){
        System.out.println(session);
        log.info("连接建立{}",userName);
        onlineSessions.put(userName,session);
    }

    @OnClose
    public void onClose(@PathParam("userName")String userName) {
        log.info("关闭{}",userName);
        onlineSessions.remove(userName);
    }

    @OnError
    public void onError(Throwable e){
        log.info("错误{}",e);
    }

    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        System.out.println(session);
        JSONObject jsonObject = JSON.parseObject(message);
        String username = jsonObject.getString("username");
        String message1 = jsonObject.getString("message");
        SensitiveFilter sensitiveFilter = new SensitiveFilter();
        String filter = sensitiveFilter.filter(message1);
        if(EmojiUntil.containsEmoji(filter)){                  //如果含有emoji符号就把聊天记录转码一下
            filter= EmojiUntil.emojiConverterToAlias(filter);
        }
        String friend_name = jsonObject.getString("friend_Name");
        int id = (int) ((Math.random() * 9 + 1) * 100000);
        Date createTime = new Date();
        Record record = new Record(id, username, friend_name, filter, createTime);
            Session session1 = onlineSessions.get(friend_name);
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("message",filter);
            jsonObject1.put("friendName",username);
            chatMapper.oneChat(record);    //把消息记录存入数据库中
            if(session1!=null){
                session1.getBasicRemote().sendText(jsonObject1.toJSONString());
            }else {
                unreadNumMapper.addMessageNum(username,friend_name);
            }

        log.info("消息数据为{}",message);
    }
}